package com.example.gulimall.product.service.impl;

import com.example.gulimall.common.to.SkuReductionTo;
import com.example.gulimall.common.to.SpuBoundTo;
import com.example.gulimall.common.utils.R;
import com.example.gulimall.product.entity.*;
import com.example.gulimall.product.feign.CouponFeignService;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gulimall.common.utils.PageUtils;
import com.example.gulimall.common.utils.Query;

import com.example.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
@Autowired
private SpuInfoDescService spuInfoDescService;
@Autowired
private SpuImagesService spuImagesService;
@Autowired
private CouponFeignService couponFeignService;
@Autowired
private ProductAttrValueService productAttrValueService;
@Autowired
private SkuInfoService skuInfoService;
@Autowired
private AttrService attrService;
@Autowired
private SkuSaleAttrValueService skuSaleAttrValueService;
@Autowired
private SkuImagesService skuImagesService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //保存spu相关基本信息 spu_info
         //保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
       spuInfoEntity.setCreateTime(new java.util.Date());
       spuInfoEntity.setUpdateTime(new Date());
       this.save(spuInfoEntity);
         //保存描述信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);
        // 保存图片信息
        List<String> images = spuSaveVo.getImages();
        if(images!=null&&images.size()!=0){
            List<SpuImagesEntity> spuImagesEntityList = images.stream().map((image -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                return spuImagesEntity;
            })).filter(entity->{
                        //返回true是需要，返回false是过滤掉
                        return !StringUtils.isEmpty(entity.getImgUrl());
                    })
                    .collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntityList);
        }
         //保存规格参数
        List<BaseAttrs> baseAttrsList = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrsList.stream().map((baseAttrs -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(baseAttrs.getAttrId());
            productAttrValueEntity.setAttrName(attrService.getAttrInfo(baseAttrs.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(baseAttrs.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttrs.getShowDesc());
            return productAttrValueEntity;
        })).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);
        //保存积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }

        //保存spu对应的sku信息
        List<Skus> skusList = spuSaveVo.getSkus();
        if(skusList!=null&&skusList.size()!=0){
            skusList.forEach(item-> {
                String defaultImg="";
                //查找默认图片
                List<Images> imagesList = item.getImages();
                for (Images image : imagesList) {
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                if(!StringUtils.isEmpty(defaultImg)){
                    skuInfoEntity.setSkuDefaultImg(defaultImg);
                }
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.save(skuInfoEntity);
                //保存sku图片信息
                List<SkuImagesEntity> skuImagesEntityList = imagesList.stream().map((images1 -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(images1, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                })).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);
                //保存sku销售信息
                List<Attr> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map((attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                })).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                //保存优惠满减信息

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                //过滤小于等于0的优惠信息
                if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R saveSkuReduction = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(saveSkuReduction.getCode()!=0){
                        log.error("远程保存优惠信息失败");
                    }
                }


            });
        }


    }
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityLambdaQueryWrapper = new QueryWrapper<>();
        String catelogId = (String) params.get("catelogId");
        if(!com.mysql.cj.util.StringUtils.isNullOrEmpty(catelogId)&& !"0".equalsIgnoreCase(catelogId)){
            spuInfoEntityLambdaQueryWrapper.lambda().eq(SpuInfoEntity::getCatalogId,catelogId);
        }
        String brandId = (String) params.get("brandId");
        if(!com.mysql.cj.util.StringUtils.isNullOrEmpty(brandId)&& !"0".equalsIgnoreCase(brandId)){
            spuInfoEntityLambdaQueryWrapper.lambda().eq(SpuInfoEntity::getBrandId,brandId);
        }
        String status = (String) params.get("status");
        if (!com.mysql.cj.util.StringUtils.isNullOrEmpty(status)){
            spuInfoEntityLambdaQueryWrapper.lambda().eq(SpuInfoEntity::getPublishStatus,status);
        }

        String key = (String) params.get("key");
        if (!com.mysql.cj.util.StringUtils.isNullOrEmpty(key)){
            spuInfoEntityLambdaQueryWrapper.and((w->{
                w.lambda().eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
            }));


        }
        IPage<SpuInfoEntity> page= this.page(new Query<SpuInfoEntity>().getPage(params),spuInfoEntityLambdaQueryWrapper);

        return new PageUtils(page);
    }

}
